import React, { useState } from 'react';
import axios from 'axios';
import { getUploadToken } from '../services/api';

const uploaderStyle = {
  marginTop: '20px',
  padding: '20px',
  border: '2px dashed var(--border-color)',
  borderRadius: 'var(--border-radius)',
  textAlign: 'center',
  backgroundColor: 'var(--light-color)',
  transition: 'border-color 0.3s ease',
};

const uploaderHoverStyle = {
  ...uploaderStyle,
  borderColor: 'var(--primary-color)',
};

const inputStyle = {
  display: 'none',
};

const previewStyle = {
  width: '100px',
  height: '100px',
  marginTop: '15px',
  borderRadius: 'var(--border-radius)',
  objectFit: 'cover',
};

const ImageUploader = ({ onUploadSuccess }) => {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');
  const [preview, setPreview] = useState(null);
  const [isHovering, setIsHovering] = useState(false);

  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    setUploading(true);
    setError('');
    setPreview(URL.createObjectURL(file));

    try {
      const tokenResponse = await getUploadToken();
      const { token, domain } = tokenResponse.data;

      const formData = new FormData();
      formData.append('file', file);
      formData.append('token', token);

      const qiniuResponse = await axios.post('https://upload.qiniup.com', formData);
      
      const imageUrl = `${domain}/${qiniuResponse.data.key}`;
      onUploadSuccess(imageUrl);
      setPreview(null); // Clear preview after successful upload to parent

    } catch (err) {
      console.error('Upload failed:', err);
      setError('上传失败。请重试。');
      setPreview(null);
    } finally {
      setUploading(false);
    }
  };

  return (
    <div 
      style={isHovering ? uploaderHoverStyle : uploaderStyle}
      onMouseEnter={() => setIsHovering(true)}
      onMouseLeave={() => setIsHovering(false)}
    >
      <label htmlFor="file-upload" className="btn btn-secondary">
        {uploading ? '正在上传...' : '添加照片'}
      </label>
      <input
        id="file-upload"
        type="file"
        accept="image/*"
        onChange={handleFileChange}
        style={inputStyle}
        disabled={uploading}
      />
      {preview && <img src={preview} alt="Preview" style={previewStyle} />}
      {error && <p style={{ color: 'var(--danger-color)', marginTop: '10px' }}>{error}</p>}
    </div>
  );
};

export default ImageUploader;
